<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="相关命令  MULTIEXECDISCARDWATCHUNWATCH  事务事务是一组命令的集合。3 性质 事务中的所有命令都被序列化并顺序执行。在Redis事务的执行过程中（指定的是 exec后的真正的执行过程，而不是用multi后的入队过程），永远不会执行另一个客户端发出的请求（**命令不会加塞）。 所有命令都将被执行，或者所有命令都不执行，因此Redis事务也是原子的（这句话有可能会引起争议">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis官方文档笔记 —— 事务（Transactions）">
<meta property="og:url" content="http://example.com/2021/09/16/Redis%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E7%AC%94%E8%AE%B0%20%E2%80%94%E2%80%94%20%E4%BA%8B%E5%8A%A1%EF%BC%88Transactions%EF%BC%89/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="相关命令  MULTIEXECDISCARDWATCHUNWATCH  事务事务是一组命令的集合。3 性质 事务中的所有命令都被序列化并顺序执行。在Redis事务的执行过程中（指定的是 exec后的真正的执行过程，而不是用multi后的入队过程），永远不会执行另一个客户端发出的请求（**命令不会加塞）。 所有命令都将被执行，或者所有命令都不执行，因此Redis事务也是原子的（这句话有可能会引起争议">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-15T16:00:00.000Z">
<meta property="article:modified_time" content="2021-12-01T02:19:14.461Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="NoSQL">
<meta property="article:tag" content="Redis">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/09/16/Redis%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E7%AC%94%E8%AE%B0%20%E2%80%94%E2%80%94%20%E4%BA%8B%E5%8A%A1%EF%BC%88Transactions%EF%BC%89/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/09/16/Redis%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E7%AC%94%E8%AE%B0%20%E2%80%94%E2%80%94%20%E4%BA%8B%E5%8A%A1%EF%BC%88Transactions%EF%BC%89/","path":"2021/09/16/Redis官方文档笔记 —— 事务（Transactions）/","title":"Redis官方文档笔记 —— 事务（Transactions）"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Redis官方文档笔记 —— 事务（Transactions） | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8B%E5%8A%A1"><span class="nav-number">1.</span> <span class="nav-text">事务</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%A7%E8%B4%A8"><span class="nav-number">1.1.</span> <span class="nav-text">性质</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%A8%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">用法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8B%E5%8A%A1%E4%B8%AD%E7%9A%84%E9%94%99%E8%AF%AF"><span class="nav-number">1.3.</span> <span class="nav-text">事务中的错误</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%91%BD%E4%BB%A4%E6%8E%92%E9%98%9F%E5%85%A5%E9%98%9F%E9%94%99%E8%AF%AF"><span class="nav-number">1.3.1.</span> <span class="nav-text">命令排队入队错误</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%91%BD%E4%BB%A4%E6%89%A7%E8%A1%8C%E9%94%99%E8%AF%AF"><span class="nav-number">1.3.2.</span> <span class="nav-text">命令执行错误</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88Redis%E4%B8%8D%E6%94%AF%E6%8C%81%E5%9B%9E%E6%BB%9A"><span class="nav-number">1.4.</span> <span class="nav-text">为什么Redis不支持回滚</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#DISCARD%E5%91%BD%E4%BB%A4%E9%98%9F%E5%88%97"><span class="nav-number">1.5.</span> <span class="nav-text">DISCARD命令队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WATCH%E5%AE%9E%E7%8E%B0%E4%B9%90%E8%A7%82%E9%94%81"><span class="nav-number">1.6.</span> <span class="nav-text">WATCH实现乐观锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis%E8%84%9A%E6%9C%AC%E5%92%8C%E4%BA%8B%E5%8A%A1"><span class="nav-number">1.7.</span> <span class="nav-text">Redis脚本和事务</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ACID"><span class="nav-number">2.</span> <span class="nav-text">ACID</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/16/Redis%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E7%AC%94%E8%AE%B0%20%E2%80%94%E2%80%94%20%E4%BA%8B%E5%8A%A1%EF%BC%88Transactions%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Redis官方文档笔记 —— 事务（Transactions） | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Redis官方文档笔记 —— 事务（Transactions）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-09-16 00:00:00" itemprop="dateCreated datePublished" datetime="2021-09-16T00:00:00+08:00">2021-09-16</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2021-12-01 10:19:14" itemprop="dateModified" datetime="2021-12-01T10:19:14+08:00">2021-12-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Redis/" itemprop="url" rel="index"><span itemprop="name">Redis</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p><strong>相关命令</strong></p>
<blockquote>
<p>MULTI<br>EXEC<br>DISCARD<br>WATCH<br>UNWATCH</p>
</blockquote>
<h1 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h1><p>事务是一组命令的集合。3</p>
<h2 id="性质"><a href="#性质" class="headerlink" title="性质"></a>性质</h2><ul>
<li>事务中的<strong>所有命令都被序列化并顺序执行</strong>。在Redis事务的执行过程中（指定的是 <code>exec</code>后的真正的执行过程，而不是用<code>multi</code>后的入队过程），永远不会执行另一个客户端发出的请求（**命令不会加塞）。</li>
<li>所有命令都将被执行，或者所有命令都不执行，因此<strong>Redis事务也是原子的</strong>（这句话有可能会引起争议）。</li>
</ul>
<h2 id="用法"><a href="#用法" class="headerlink" title="用法"></a>用法</h2><p>使用<code>MULTI</code>命令输入Redis事务。该命令始终以答复OK。<br>此时，用户可以发出多个命令。<strong>Redis不会执行这些命令，而是将它们排队。</strong><br><strong>一旦调用EXEC，将执行所有命令。</strong>，并且<strong>EXEC返回了一个答复数组</strong>，其中每个元素都是事务中单个命令的答复，其发出顺序与命令相同。<br>如：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; MULTI</span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; SET k1 v1</span><br><span class="line">QUEUED</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; SET k2 v2</span><br><span class="line">QUEUED</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; GET k1</span><br><span class="line">QUEUED</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; EXEC</span><br><span class="line"><span class="number">1</span>) OK</span><br><span class="line"><span class="number">2</span>) OK</span><br><span class="line"><span class="number">3</span>) <span class="string">&quot;v1&quot;</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; </span><br></pre></td></tr></table></figure>
<p>需要强调的是，<code>MULTI</code>之后的命令并不会执行，它们只是入队而已，知道<code>EXEC</code>命令发出，所有命令才会一起执行。</p>
<h2 id="事务中的错误"><a href="#事务中的错误" class="headerlink" title="事务中的错误"></a>事务中的错误</h2><h3 id="命令排队入队错误"><a href="#命令排队入队错误" class="headerlink" title="命令排队入队错误"></a>命令排队入队错误</h3><p>这种常见的错误有 ① 命令不存在 ② 命令参数的个数不对。<br>这种错误一旦发生，<strong>这个事务就会失败，也就是说事务中的命令全都不会执行</strong>。<br>如：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; multi</span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set a <span class="number">1</span></span><br><span class="line">QUEUED</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get b <span class="number">1</span></span><br><span class="line">(<span class="built_in">error</span>) ERR wrong number of arguments <span class="keyword">for</span> <span class="string">&#x27;get&#x27;</span> command</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set c <span class="number">3</span></span><br><span class="line">QUEUED</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; exec</span><br><span class="line">(<span class="built_in">error</span>) EXECABORT Transaction discarded because of previous errors.</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; </span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; </span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get a</span><br><span class="line">(<span class="literal">nil</span>)</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get c</span><br><span class="line">(<span class="literal">nil</span>)</span><br></pre></td></tr></table></figure>

<p>可见即使是正确的命令也没有执行成功。</p>
<blockquote>
<p>从Redis 2.6.5开始，服务器会记住命令累积期间发生错误，并且将拒绝执行事务，并且在EXEC期间还会返回错误并自动丢弃该事务。</p>
</blockquote>
<h3 id="命令执行错误"><a href="#命令执行错误" class="headerlink" title="命令执行错误"></a>命令执行错误</h3><p>常见的有，命令与键的类型冲突，给一个字符串类型的键自增但是键值不是数字，等等。</p>
<p>EXEC之后发生的错误不会以特殊方式处理:<strong>即使在事务期间某些命令失败，也会执行所有其他命令</strong>。<br>也正是因为一点，让Redis事务的原子性受到质疑。</p>
<p>如：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; SET a hello</span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; MULTI</span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; INCR a</span><br><span class="line">QUEUED</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; SET b <span class="number">2</span></span><br><span class="line">QUEUED</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; EXEC</span><br><span class="line"><span class="number">1</span>) (<span class="built_in">error</span>) ERR value is <span class="keyword">not</span> an integer <span class="keyword">or</span> out of range</span><br><span class="line"><span class="number">2</span>) OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; GET b</span><br><span class="line"><span class="string">&quot;2&quot;</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; </span><br></pre></td></tr></table></figure>
<p>即使在<code>INCR</code>命令执行错误之后，可以看到之后的合法的命令仍然执行成功了。</p>
<h2 id="为什么Redis不支持回滚"><a href="#为什么Redis不支持回滚" class="headerlink" title="为什么Redis不支持回滚"></a>为什么Redis不支持回滚</h2><p>大致有三点原因：</p>
<ol>
<li>程序员自身犯的错误是无法避免的。</li>
<li>不支持回滚可以使得Redis事务的实现更加高效。</li>
<li>发生错误一般发生在开发过程中，不太可能进入到生产环境中。</li>
</ol>
<h2 id="DISCARD命令队列"><a href="#DISCARD命令队列" class="headerlink" title="DISCARD命令队列"></a>DISCARD命令队列</h2><p>之前说，一旦客户端给Redis服务器发送一个<code>MULTI</code>此时，Redis受到的命令不会立即执行，而是存储在队列里。<br>也就是此时客户端和服务器的连接状态进入一种<strong>事务状态</strong>。<br><strong>而<code>DISCARD</code>命令相反，它用来结束这种状态的，当然之前队列里的命令组也会被清空。</strong>	</p>
<p>注意，此命令只在客户端和服务器之间有<code>MULTI</code>执行之后，才会返回<strong>OK</strong>,否则返回<br><strong>(error) ERR DISCARD without MULTI</strong>。</p>
<h2 id="WATCH实现乐观锁"><a href="#WATCH实现乐观锁" class="headerlink" title="WATCH实现乐观锁"></a>WATCH实现乐观锁</h2><blockquote>
<p><code>WATCH</code>用于为Redis事务提供检查设置（CAS check-ans-set）行为。</p>
</blockquote>
<p>被WATCH的键，如果在事务执行（exec）前发生了变化，那么之后事务就不会执行，返回（null）。</p>
<p>下面的实现自增<code>INCR</code>命令组在多个客户端并发访问服务器的时候，就会产生竞争条件。<br>比如，一开始键的值的是10，向后两个客户端执行了自增命令，最终值应该是12。<br>但是，两个客户端可能先后拿到10，然后分别自增，最后分别赋值11。<br>就出现错误。</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">val = GET mykey</span><br><span class="line">val = val + <span class="number">1</span></span><br><span class="line">SET mykey $val</span><br></pre></td></tr></table></figure>

<p>可能初学者，有这样的想法，将这组命令当成一个事务执行，不就解决问题了吗。<br>不过，事务执行的结果是在<code>exec</code>之后才能拿到的，无法中途拿到（其次你也要知道的是 multi 之后也是不加任何锁的）</p>
<p>这个时候就需要<code>WATCH</code>命令了。<br>不妨换思路，</p>
<ol>
<li>监控我们需要自增的键。</li>
<li>然后获取键值，并让值加1。</li>
<li>最后用<code>set</code>命令赋值。如果，在赋值的时候，发现值已经被另一个客户端修改了，这个时候如果还去set就会出现上面的情况，所以此次事务就放弃执行。</li>
</ol>
<p><strong>基于这个思路，我们采取先check后set的方式，执行事务，如果事务失败，再执行一次，并期望这次没有产生冲突，直到这个事务执行成功。</strong><br>这种锁的形式成为<strong>乐观锁</strong>。</p>
<p>最终借助<code>WATCH</code>和事务实现了自增命令如下：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">WATCH mykey</span><br><span class="line">val = GET mykey</span><br><span class="line">val = val + <span class="number">1</span></span><br><span class="line">MULTI</span><br><span class="line">SET mykey $val</span><br><span class="line">EXEC</span><br></pre></td></tr></table></figure>

<p>关于<code>watch</code>命令还有如下补充：</p>
<ul>
<li><code>watch</code> 可以在<code>multi</code>之前多次调用，并且可以一次watch多个键，只要有一个键被改变，事务就不会执行。</li>
<li>当<code>exec</code>被调用时，所有键都会恢复 <strong>UNWATCHED</strong> 的状态，不管事务是否中止与否。<br>同样，当客户端连接关闭时，所有键都会被<strong>UNWATCHED</strong>。</li>
<li>也可以使用<code>unwatch</code>命令（不带参数）来刷新所有监视的键。</li>
<li>注意，很重要的一点是，<strong>键是否被监控都是相对于每个客户端而言的，也就是说它不是对于服务器的一个全局状态</strong>。以后会在Redis的实现里具体探讨。</li>
</ul>
<p>一个例子：有序集合zset是没有弹出第一个元素的原子性命令的，我们可以使用watch和事务实现它。<br><strong>使用WATCH实现ZPOP</strong></p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">WATCH zset</span><br><span class="line">element = ZRANGE zset <span class="number">0</span> <span class="number">0</span></span><br><span class="line">MULTI</span><br><span class="line">ZREM zset element</span><br><span class="line">EXEC</span><br></pre></td></tr></table></figure>

<p>如果EXEC失败（即返回Null答复），我们将重复该操作。</p>
<h2 id="Redis脚本和事务"><a href="#Redis脚本和事务" class="headerlink" title="Redis脚本和事务"></a>Redis脚本和事务</h2><blockquote>
<p>一个Redis的脚本是定义事务性的，所以一切都可以用Redis的事务做的，你也可以用一个脚本做的，平时脚本会更简单，更快速。<br>这种重复是由于以下事实：脚本是在Redis 2.6中引入的，而事务早已存在。但是，我们不太可能在短期内取消对事务的支持，因为在语义上似乎是适当的，即使不诉诸Redis脚本，仍然有可能避免竞争状况，尤其是因为Redis事务的实现复杂性极低。<br>但是，在不久的将来，我们会看到整个用户群只是在使用脚本，这并非不可能。如果发生这种情况，我们可能会弃用并最终删除事务。</p>
</blockquote>
<h1 id="ACID"><a href="#ACID" class="headerlink" title="ACID"></a>ACID</h1><p>与关系型数据库ACID的对比。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/NoSQL/" rel="tag"># NoSQL</a>
              <a href="/tags/Redis/" rel="tag"># Redis</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/09/16/%E5%85%B3%E4%BA%8ESpring%E8%87%AA%E5%8A%A8%E9%85%8D%E7%BD%AE%E7%9A%84%E4%B8%80%E4%BA%9B%E6%B3%A8%E8%A7%A3/" rel="prev" title="关于Spring自动配置的一些注解">
                  <i class="fa fa-chevron-left"></i> 关于Spring自动配置的一些注解
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/09/16/Redis%E5%9C%A8Java%20%E8%AF%AD%E8%A8%80%E7%9A%84%E4%BD%BF%E7%94%A8%20%E2%80%94%E2%80%94%20%E4%BD%BF%E7%94%A8%20Jedis%20%E6%B5%8B%E8%AF%95%20redis%E6%93%8D%E7%BA%B5%E5%87%A0%E7%A7%8D%E5%B8%B8%E8%A7%81%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%91%BD%E4%BB%A4/" rel="next" title="Redis在Java 语言的使用 —— 使用 Jedis 测试 redis操纵几种常见数据类型的命令">
                  Redis在Java 语言的使用 —— 使用 Jedis 测试 redis操纵几种常见数据类型的命令 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
